package cn.jtool.dig.client.comm.tunnel.protocol;

import cn.jtool.dig.client.comm.VirtualManager;
import cn.jtool.dig.client.comm.tunnel.TunnelAttrKey;
import cn.jtool.dig.common.model.Commands;
import cn.jtool.dig.common.model.Packet;
import cn.jtool.dig.common.model.PacketBody;
import cn.jtool.dig.common.netty.CtxUtils;
import cn.jtool.dig.common.netty.ProtocolProcess;
import cn.jtool.dig.common.netty.TcpClient;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
public class P_10_CommonResponse implements ProtocolProcess {

    @Override
    public int protocolId() {
        return Commands.COMMON_RESPONSE.getCode();
    }
    @Override
    public Packet process(ChannelHandlerContext ctx, Packet packet) {
        PacketBody body = packet.getBody();
        int cmd = body.readByte();
        long sn = body.readWord();
        int result = body.readByte();
        log.info("[Tunnel]通用应答: {} {} {}", Commands.valueOfCode(cmd).getName(), sn, result == 0 ? "成功" : "失败");

        if (cmd == Commands.CLOSE_SESSION.getCode() && result == 0 && packet.getHeader().getChannelId() != 0){
            VirtualManager.removeClient(packet.getHeader().getChannelId());
        }

        if(cmd == Commands.DATA_TRANSPARENT.getCode() && result == 0x01){
            TcpClient client = VirtualManager.getClient(packet.getHeader().getChannelId());
            if(Objects.nonNull(client)){
                client.stop();
            }
        }

        if(cmd == Commands.AUTH.getCode()){
            if(result == 0x00){
                log.info("登录成功");
            }else{
                log.info("登录失败");
                CtxUtils.setAttribute(ctx, TunnelAttrKey.AUTH_STATUS, result);
                ctx.channel().closeFuture();
            }
        }
        return null;
    }
}
